package cz.fel.via.timemanagement;

import java.util.List;
import java.util.Set;

import cz.cvut.fel.via.kosapirest.Fasade;
import cz.cvut.fel.via.kosapirest.domain.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class ScheduleActivity extends Activity {

	private final static int ONLY_ME_NOTES = 15;
	private final static int ONLY_ME_EXAMS = 25;
	String username;
	Context cnt; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.schedule);
		
		cnt = this;
		
		username = (String) TimeManagement.getKey("username");
		if (username == null) {
			username = TimeManagement.getUser();
		}
		Fasade fasade = TimeManagement.getFasade();
		Student student = fasade.find(username, Student.class);

		//TODO kdyz je blbe username ;)
		
		TextView name = (TextView) findViewById(R.id.studentName);
		name.setText(student.getFirstName()+" "+student.getLastName());
		name.setGravity(Gravity.CENTER_HORIZONTAL);
		
		// 0-4 sude (% 5 = 0; 0 je suda); 0 a 5 = pondeli, ... 
		// 5-9 liche (% 5 = 1)
		Day[] days = new Day[10];
		for (int i = 0; i < days.length; i++) {
			days[i] = new Day();
		}
		List<Parallel> paralels = fasade.findStudentParallels(username);
		
		for (Parallel parallel : paralels) {
			Course c = fasade.find(parallel.getCourse(), Course.class);
			
			Set<TimetableSlot> slots = parallel.getTimetableSlot();
			for (TimetableSlot timetableSlot : slots) {
				int day = timetableSlot.getDay();
				day--;
				Slot s = new Slot(parallel, c, timetableSlot.getRoom(), timetableSlot.getDuration());
				
				switch (timetableSlot.getParity()) {
				case BOTH:
					//vyuka jen v obou tydnech
					days[day].slots[timetableSlot.getFirstHour()] = s;
					days[day+5].slots[timetableSlot.getFirstHour()] = s;
					break;
					
				case EVEN:
					//vyuka jen v sudem tydnu
					days[day].slots[timetableSlot.getFirstHour()] = s;
					break;
				
				case ODD:
					//vyuka jen v lichem tydnu
					day += 5;
					days[day].slots[timetableSlot.getFirstHour()] = s;
					break;
				
				}
			}
		}
		//tak, a ted je rozvrh na jednotlive tydny naplnen.
		//bohuzel neni mozne zjistit, jaky je ted tyden. 
		//mozna to odpovida kalendarnimu tydnu
		//neni to ale jiste, takze zobrazime oba dva tydny.
				
		
		//stejne rozmery okynek:
		int pxWidth = 70;//sirka okna v pixelech, u predmetu trvajcich 2 hodiny (vetsina) je sirka dvojnasobna 
		int pxHeight = 100; //vyska okna v pixelech
		//nemam vubec poneti, zda ty rozmery sedi, ale daji se snadno zmenit.
		
		
		LayoutParams params = new LayoutParams(pxWidth, pxHeight);
		LayoutParams params2hour = new LayoutParams(2*pxWidth, pxHeight);
		LayoutParams paramsWrap = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		
		LinearLayout timetable = (LinearLayout) findViewById(R.id.schedule);
		//timetable.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		LinearLayout header = (LinearLayout) findViewById(R.id.header);
		LinearLayout firstLine = new LinearLayout(this);
		//casy
		for (int i = -2; i < 14; i++) {
			LinearLayout showingTime = new LinearLayout (this);
			showingTime.setLayoutParams(params);
			showingTime.setOrientation(LinearLayout.VERTICAL);
			//a ted se tam musi narvat casy, -1 zustane volne (nade dnem)
			//casy se mohou lisit podle fakulty, FEL a FIT je ale maji shodne a jine fakulty zas nemaj Kos API

			TextView start = new TextView(this);
			start.setText(Hours.getStart(i));
			TextView end = new TextView(this);
			end.setText(Hours.getEnd(i));
			
			showingTime.addView(start);
			showingTime.addView(end);
			
			firstLine.addView(showingTime);
		}
		
		header.addView(firstLine);
		
		
		
		TextView evenWeek = new TextView(this);
		evenWeek.setText(R.string.evenWeek);
		evenWeek.setTextSize(18);
		evenWeek.setTextColor(Color.CYAN);
		evenWeek.setTextAppearance(this, android.R.attr.textAppearanceLarge);
		timetable.addView(evenWeek);
		
		//ano, je to prasacky cyklus. :-)
		for (int i = 0; i < days.length; i++) {
			
			if (i == 5) {
				TextView oddWeek = new TextView(this);
				oddWeek.setText(R.string.oddWeek);
				oddWeek.setTextAppearance(this, android.R.attr.textAppearanceLarge);
				oddWeek.setTextSize(18);
				oddWeek.setTextColor(Color.CYAN);
				oddWeek.setPadding(0, 30, 0, 0);
				timetable.addView(oddWeek);
			}
			

			LinearLayout oneDay = new LinearLayout(this);
			oneDay.setLayoutParams(paramsWrap);
			oneDay.setOrientation(LinearLayout.HORIZONTAL);
			
			TextView dayInWeek = new TextView(this);
			dayInWeek.setLayoutParams(params);
			switch (i % 5) {
			case 0:
				dayInWeek.setText(R.string.monday);
				break;
			case 1:
				dayInWeek.setText(R.string.tuesday);
				break;
			case 2:
				dayInWeek.setText(R.string.wednesday);
				break;
			case 3:
				dayInWeek.setText(R.string.thursday);
				break;
			case 4:
				dayInWeek.setText(R.string.friday);
				break;
			}
			oneDay.addView(dayInWeek);
			
			for (int j = 0; j < 14; j++) {
				final Slot s = days[i].slots[j];
				if (s == null) {
					LinearLayout time = new LinearLayout(this);
					time.setLayoutParams(params);
					oneDay.addView(time);
				} else {
					LinearLayout time = new LinearLayout(this);
					time.setOrientation(LinearLayout.VERTICAL);
					if (s.duration == 1) {
						time.setLayoutParams(params);	
					} else if (s.duration == 2) {
						time.setLayoutParams(params2hour);
						j++;
					} else {
						time.setLayoutParams(new LayoutParams(s.duration*pxWidth, pxHeight));
						j += (s.duration-1);
						//nastavi prislusnou sirku
					}
					
					//tady se vytvori textViews a nasype se do nich obsah
					//viz udb
					TextView courseCode = new TextView(this);
					SpannableString content = new SpannableString(s.course.getCodeShort());
					content.setSpan(new UnderlineSpan(), 0, s.course.getCodeShort().length(), 0);
					courseCode.setText(content);
					courseCode.setTextColor(Color.rgb(204, 0, 0));
					
					
					//zobrazi kratky kod predmetu
					
					TextView room = new TextView(this);
					room.setText(s.room);
					
					TextView teachers = new TextView(this);
					StringBuilder teachersString = new StringBuilder();
					
					for (String string : s.parallel.getTeachers()) {
						teachersString.append(string);
						teachersString.append(", ");
					}
					if(teachersString.toString().isEmpty()){
						teachersString.append("empty");
					}
					//teachersString.delete(teachersString.length()-2, teachersString.length());
					//odstrani posledni carku a mezeru
					teachers.setText(teachersString.toString());
					
					time.setOnClickListener(new OnClickListener () {
						public void onClick(View v) {
							TimeManagement.putKey("course", s.course.getCode());
							
							Intent intent = new Intent(cnt, OneCourseActivity.class);
							startActivity(intent);
						}
						
					});
					
					time.addView(courseCode);
					time.addView(room);
					time.addView(teachers);
					time.setBackgroundResource(R.drawable.background);
					
					
					
					oneDay.addView(time);
					
				}
			}
			
			ImageView separator = new ImageView(cnt);
	        separator.setImageResource(R.drawable.horizontal);
	        separator.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT ));
	        separator.setScaleType(ScaleType.FIT_XY);
	        separator.setPadding(25, 0, 25, 0);
	        
	        timetable.addView(separator);
			timetable.addView(oneDay);
		}
		
		//nakonec musime tento pracne vytvoreny layout hodit do okna
		//ne, nemusime, cpeme to do toho layoutu co je potreba :-) 
	}
	
	public void student(View v) {
		TimeManagement.putKey("username", username);
		
		Intent intent = new Intent(this, StudentActivity.class);
		startActivity(intent);
	}
	
	public void exams(View v) {
		if (username.equals(TimeManagement.getUser())) {
			Intent intent = new Intent(this, ExamActivity.class);
			startActivity(intent);
		} else {
			showDialog(ONLY_ME_NOTES);
		}
	}
	
	public void notes(View v) {
		if (username.equals(TimeManagement.getUser())) {
			Intent intent = new Intent(this, NoteActivity.class);
			startActivity(intent);
		} else {
			showDialog(ONLY_ME_EXAMS);
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ONLY_ME_NOTES:
			AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
			alertbox.setMessage(R.string.onlyMeNotes);
			alertbox.setNeutralButton("Ok", null);
			return alertbox.show();
		case ONLY_ME_EXAMS:
			AlertDialog.Builder alertbox1 = new AlertDialog.Builder(this);
			alertbox1.setMessage(R.string.onlyMeExams);
			alertbox1.setNeutralButton("Ok", null);
			return alertbox1.show();
		}
		return null;
	}
}

class Day {
	int id;
	Slot[] slots = new Slot[14];
	
}

class Slot {
	private static int count = 0;
	private int id;
	int duration;
	
	Parallel parallel;
	Course course;
	String room;
	
	Slot(Parallel parallel, Course course, String room, int duration) {
		this.parallel = parallel;
		this.course = course;
		this.duration = duration;
		this.room = room;
		id = count++;
	}
	
	int getId() {
		return id;
	}
	
	@Override
	public boolean equals(Object o) {
		Slot s = (Slot) o;
		if (s.getId() == id) {
			return true;
		}
		return false;
	}
}

class Hours {
	
	static String getStart(int i) {
		switch (i) {
		case 0:
			return "7:30";
		case 1:
			return "8:15";
		case 2:
			return "9:15";
		case 3:
			return "10:00";
		case 4:
			return "11:00";
		case 5:
			return "11:45";
		case 6:
			return "12:45";
		case 7:
			return "13:30";
		case 8:
			return "14:30";
		case 9:
			return "15:15";
		case 10:
			return "16:15";
		case 11:
			return "17:00";
		case 12:
			return "18:00";
		case 13:
			return "18:45";
		}
		return "";
	} 
	
	static String getEnd(int i) {
		switch (i) {
		case 0:
			return "8:15";
		case 1:
			return "9:00";
		case 2:
			return "10:00";
		case 3:
			return "10:45";
		case 4:
			return "11:45";
		case 5:
			return "12:30";
		case 6:
			return "13:30";
		case 7:
			return "14:15";
		case 8:
			return "15:15";
		case 9:
			return "16:00";
		case 10:
			return "17:00";
		case 11:
			return "17:45";
		case 12:
			return "18:45";
		case 13:
			return "19:30";
		}
		return "";
	}
}
